#include "archive.hpp"
#include <fstream>
namespace fur
{
   Archive::Archive(std::ifstream &infile)
      :is(infile)
   {
   }
   
   Archive::~Archive()
   {
   }

   void Archive::extract_a_file(FileHead *filehead)
   {
      std::ofstream outfile(filehead->get_filename(), std::ios::out|std::ios::binary);
      Unpack unpack(is, outfile, *filehead);
      unpack.do_unpack();
   }
   
   
   void Archive::extract()
   {
      size_t inposi = 0;
      check_rarhead(is);
      inposi += 7;
      BaseHead *mainhead = new BaseHead;
      read_head(mainhead, is);
      inposi += mainhead->get_headsize();
      if (mainhead->get_headtype() != HeadType::MAIN)
      {
	 throw EUnpack(__func__);
      }
      delete mainhead;
      bool endstatus = false;
      while (true)
      {
	 BaseHead *newhead = new BaseHead;
	 read_head(newhead, is);
	 inposi += newhead->get_headsize();
	 switch (newhead->get_headtype())
	 {
	    case HeadType::FILE:
	    {
	       FileHead *filehead = dynamic_cast<FileHead*>(newhead);
	       extract_a_file(filehead);
	       inposi += filehead->get_packsize();
	       is.clear();
	       is.seekg(inposi);
	    }
	    break;
	    case HeadType::END:
	       endstatus = true;
	       break;
	    default:
	       throw EUnsupport(__func__);
	 }
	 delete newhead;
	 if (endstatus)
	 {
	    break;
	 }
      }
   }
}
